package com.easyadmin.controller;

import com.easyadmin.annotation.GlobalInterceptor;
import com.easyadmin.annotation.VerifyParam;
import com.easyadmin.config.ApiConfig;
import com.easyadmin.entity.constants.Constants;
import com.easyadmin.entity.dto.SessionUserDto;
import com.easyadmin.entity.enums.OperModuleEnum;
import com.easyadmin.entity.enums.PermissionCodeEnum;
import com.easyadmin.entity.enums.VerifyRegexEnum;
import com.easyadmin.entity.po.CreateImageCode;
import com.easyadmin.entity.vo.AjaxResponseVO;
import com.easyadmin.exception.BusinessException;
import com.easyadmin.service.SysAccountService;
import com.easyadmin.service.SysMenuService;
import com.easyadmin.utils.StringTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Random;

@RestController
@RequestMapping("/api")
public class LoginController extends ABaseController {

    private final Logger logger = LoggerFactory.getLogger(getCode());

    @Resource
    private SysAccountService sysAccountService;

    @Resource
    private SysMenuService sysMenuService;

    @Resource
    private ApiConfig apiConfig;

    /**
     * @Description: 验证码
     * @auther: 多多洛
     * @date: 14:50 2020/11/7
     * @param: [request, response, session]
     * @return: void
     */
    @RequestMapping(value = "/checkCode")
    public void checkCode(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws
            IOException {
        CreateImageCode vCode = new CreateImageCode(130, 38, 5, 10);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        String code = vCode.getCode();
        session.setAttribute(Constants.CHECK_CODE_KEY, code);
        vCode.write(response.getOutputStream());
    }

    private static String getCode() {
        char[] codeSequence = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
                'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};
        StringBuffer randomCode = new StringBuffer();
        Random random = new Random();
        int codeCount = 4;
        int codeSequenceLength = codeSequence.length;
        for (int i = 0; i < codeCount; i++) {
            String strRand = String.valueOf(codeSequence[random.nextInt(codeSequenceLength)]);
            randomCode.append(strRand);
        }
        return randomCode.toString();
    }

    @RequestMapping("/login")
    @GlobalInterceptor(permissionCode = PermissionCodeEnum.NO_PERMISSION, opObject = OperModuleEnum.OBJECT_LOGIN, opDescription = "登录账号:#{#param1}")
    public AjaxResponseVO login(HttpSession session, @VerifyParam(required = true) String account, @VerifyParam(required = true) String password,
                                @VerifyParam(required = true) String checkCode) {
        try {
            if (StringTools.isEmpty(checkCode) || !checkCode.equalsIgnoreCase((String) session.getAttribute(Constants.CHECK_CODE_KEY))) {
                throw new BusinessException("图片验证码不正确");
            }
            SessionUserDto sessionUserDto = sysAccountService.login(account, password, true);
            session.setAttribute(Constants.ADMIN_SESSION_KEY, sessionUserDto);
            return getSuccessResponseVO(sessionUserDto);
        } catch (BusinessException e) {
            logger.error("登录失败", e);
            return getBusinessErrorResponseVO(e);
        } catch (Exception e) {
            logger.error("登录失败", e);
            return getServerErrorResponseVO();
        } finally {
            session.removeAttribute(Constants.CHECK_CODE_KEY);
        }
    }

    /**
     * 获取用户信息
     *
     * @param session
     * @return
     */
    @RequestMapping("/getUserInfo")
    @GlobalInterceptor(permissionCode = PermissionCodeEnum.NO_PERMISSION)
    public AjaxResponseVO getUserInfo(HttpSession session) {
        try {
            return getSuccessResponseVO(getSessionUserInfo(session));
        } catch (Exception e) {
            return getServerErrorResponseVO();
        }
    }

    @RequestMapping("/logout")
    @GlobalInterceptor(permissionCode = PermissionCodeEnum.NO_PERMISSION)
    public AjaxResponseVO logout(HttpSession session, HttpServletResponse response) {
        session.invalidate();
        Cookie cookie = new Cookie(Constants.COOKIE_KEY, "");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/updatePassword")
    @GlobalInterceptor(permissionCode = PermissionCodeEnum.NO_PERMISSION)
    public AjaxResponseVO updatePassword(HttpSession session, @VerifyParam(required = true, regex = VerifyRegexEnum.PASSWORD) String oldPassword,
                                         @VerifyParam(required = true) String password) {
        try {
            sysAccountService.updatePassword(getSessionUserInfo(session).getUserId(), oldPassword, password);
            return getSuccessResponseVO(null);
        } catch (BusinessException e) {
            logger.error("修改密码失败", e);
            return getBusinessErrorResponseVO(e);
        } catch (Exception e) {
            logger.error("修改密码失败", e);
            return getServerErrorResponseVO();
        }
    }
}
